package com.wutoon.etl.aop;

import com.alibaba.fastjson.JSON;
import com.wutoon.etl.enums.SseStage;
import com.wutoon.etl.pojo.SseOutputInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author 武兴云/72176468
 * @version 1.0
 * @date 2024/2/5 9:18
 * @description 日志上报
 */
@Slf4j
public class PowerJobLogReport {
    public static void report(String info, Object ...param) {
        try {
            if (RequestContextHolder.getRequestAttributes() == null) {
                return;
            }
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            String accept = request.getHeader("Accept");
            if (StringUtils.equals(accept, MediaType.TEXT_EVENT_STREAM_VALUE)) {
                SseOutputInfo stage = new SseOutputInfo(SseStage.REPORT.getCode(), String.format(info, param));
                assert response != null;
                response.getWriter().println("data: " + JSON.toJSONString(stage));
                response.getWriter().println();
                response.getWriter().flush();
            }
        } catch (Exception e) {
            log.error("PowerJobLogReport error");
            log.error(info, e);
        }

    }
}
